package blogadmin;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 查找数据库
 * 
 * @author shi
 *
 */
public class blog_select {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		// 1.加载注册驱动
		Class.forName("com.mysql.jdbc.Driver").newInstance();

		// 2.建立数据连接
		String url = "jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8";
		Connection conn = null;
		try {

			conn = DriverManager.getConnection(url, "root", "shihuang");
			conn.setAutoCommit(false);

			// 3.执行SQL语句
			// 建立Statement对象
			Statement stmt = conn.createStatement();

			// 做好准备工作之后就可以执行sql语句了
			String sqla = "select * from blog";

			String insertSQL = "insert into blog (title,author_id,publish_time,read_count,comment_count,content,type_id) values('Java学习test4',1,sysdate(),0,0,'Java课程的基础学习',1)";
			String insertSQL2 = "insert into blog_type (type_name,remark) values('Java Test4',nul)";

			int extRows = stmt.executeUpdate(insertSQL);
			System.out.println("影响的行数1：" + extRows);

			int extRows2 = stmt.executeUpdate(insertSQL2);
			System.out.println("影响的行数2：" + extRows2);

			System.out.println("执行sql提交");
			conn.commit();

			// 执行sql语句
			 ResultSet rs = stmt.executeQuery(sqla);

			// 4.处理数据

			while (rs.next()) {
				System.out.println(rs.getString("id"));
				System.out.println(rs.getString("title"));
			}

			// 5.关闭连接
			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException sqlE) {
			System.err.println("sql执行异常");
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}
}
